/*
 * SPI.c
 *
 * Created: 20.02.2013 15:35:54
 *  Author: saenko
 */ 
#include <avr/io.h>
#include <avr/interrupt.h>

#define cbi(reg,bit)	reg &= ~(_BV(bit))
#define sbi(reg,bit)	reg |= (_BV(bit))

#define SET_SS	sbi(PORTB,PB2)
#define CLR_SS	cbi(PORTB,PB2)

#define WR_PHASE cbi(SPCR,CPHA)
#define RD_PHASE sbi(SPCR,CPHA)

#define SPI_IDLE 0
#define SPI_READ 1
#define SPI_READ_LISTEN 2

volatile unsigned char spi_complete = 0;

volatile unsigned char spi_state = SPI_IDLE;

volatile unsigned char spi_rec;

ISR(SPI_STC_vect)
{
	cbi(PORTB,PB3);
	//spi_complete = 1;
	switch(spi_state)
	{
	case SPI_READ :
				spi_state = SPI_READ_LISTEN;
				RD_PHASE;
				SPDR = 0x00;
		break;
	case SPI_READ_LISTEN:
				spi_rec = SPDR;
				spi_state = SPI_IDLE;
				WR_PHASE;
				SET_SS;			
				spi_complete = 1;
		break;
	}
}

void spi_init(void)
{
	sbi(DDRB,PB2);
	SET_SS;
	
	sbi(DDRB,PB3);
	sbi(DDRB,PB5);
	
	
/*	SPOL = 0 SPHA = 0 - WR
		SPOL = 0 SPHA = 1 - RD*/
		
	SPCR = (1<<SPIE)|(1<<SPE)|(0<<DORD)|(1<<MSTR)|(0<<CPOL)|(0<<SPI2X)|(1<<SPR1)|(0<<SPR0);
	WR_PHASE;
}
void spi_write(unsigned char data)
{
	SPDR = data;
}

void spi_read_reg(unsigned char reg)
{
	spi_state = SPI_READ;
	WR_PHASE;
	CLR_SS;
	SPDR = reg;
}